package com.wk.oms.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wk.common.constant.mq.ItemExchange;
import com.wk.common.constant.mq.ItemQueue;
import com.wk.common.constant.mq.ItemRoutingKey;
import com.wk.oms.entity.Order;
import com.wk.oms.mapper.OrderMapper;
import com.wk.ums.vo.UserIntegralVO;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 监听订单相关操作
 */
@Component
public class OrderListener {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 支付成功后根据订单编号更改订单状态 减库存 加积分
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = ItemExchange.ORDER_EXCHANGE, ignoreDeclarationExceptions = "true"),
            value = @Queue(value = ItemQueue.PAY_SUCCESS_QUEUE, durable = "true"),
            key = ItemRoutingKey.PAY_SUCCESS
    ))
    public void paySuccess(String orderToken){
        //订单状态改为待支付
        Order order = new Order();
        order.setStatus(1);                 //UpdateWrapper是更新的where条件
        int i = orderMapper.update(order, new UpdateWrapper<Order>().eq("order_sn", orderToken).eq("status", 0));

        //如果订单状态更新成功,则减少库存 并增加积分
        if (i == 1) {
            //减库存
            amqpTemplate.convertAndSend(ItemExchange.ORDER_EXCHANGE,ItemRoutingKey.STOCK_DECREASE,orderToken);

            //加积分
            order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_sn", orderToken));
            UserIntegralVO userIntegralVO = new UserIntegralVO();
            BeanUtils.copyProperties(order, userIntegralVO);
            amqpTemplate.convertAndSend(ItemExchange.ORDER_EXCHANGE,ItemRoutingKey.INTEGRAL_INCREASE,userIntegralVO);

        }
    }


    /**
     * 监听并关闭死信队列中订单编号对应超时未付款的订单
     *
     * 死信队列在配置类中声明过 不用再次绑定 只声明需要监听的队列
     */
    @RabbitListener(queues = ItemQueue.DEAD_LETTER_QUEUE)
    public void closeOrder(String orderToken){
        //订单状态改为已关闭
        Order order = new Order();
        order.setStatus(4);                 //UpdateWrapper是更新的where条件
        int i = orderMapper.update(order, new UpdateWrapper<Order>().eq("order_sn", orderToken).eq("status", 0));

        //如果订单关闭成功,则解锁订单中的商品库存
        if (i == 1) {
            amqpTemplate.convertAndSend(ItemExchange.ORDER_EXCHANGE,ItemRoutingKey.STOCK_UNLOCK,orderToken);

        }
    }

}
